from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
# Create your views here.
from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU
from apps.goods.utils import get_breadcrumb

from utils.response_code import RETCODE

# 列表页
class ListView(View):
    def get(self, request, category_id, page_num):
        # 获取三级分类的对象
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return HttpResponseNotFound('商品分类不存在')

        # 1.商品分类数据
        from apps.contents.utils import get_categories
        categories = get_categories()

        # 2.面包屑组件数据
        from apps.goods.utils import get_breadcrumb
        breadcrumb = get_breadcrumb(category)

        # 3. 排序
        sort = request.GET.get('sort', 'default')
        # 按照排序规则查询该分类商品SKU信息
        if sort == 'price':
            # 按照价格由低到高
            sort_field = 'price'
        elif sort == 'hot':
            # 按照销量由高到低
            sort_field = '-sales'
        else:
            # 'price'和'sales'以外的所有排序方式都归为'default'
            sort_field = 'create_time'
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field)

        # 4. 分页
        # 创建分页器：每页N条记录
        paginator = Paginator(skus, 5)
        # 获取每页商品数据
        try:
            page_skus = paginator.page(page_num)
        except Exception as e:
            # 如果page_num不正确，默认给用户404
            return HttpResponseNotFound('empty page')
        # 获取列表页总页数
        total_page = paginator.num_pages

        context = {
            'categories': categories,
            'breadcrumb':breadcrumb,
            'sort': sort,  # 排序字段
            'category': category,  # 第三级分类
            'page_skus': page_skus,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num,  # 当前页码

        }
        print('*'*20,context['categories'])
        return render(request, 'list.html', context)

# 热销商品
class HotView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """提供商品热销排行JSON数据"""
        # 根据销量倒序
        try:
            skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]
        except Exception as e:
            return JsonResponse({'code':RETCODE.DBERR, 'errmsg':'没有当前的商品', 'hot_skus':[]})
        # 序列化
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'default_image_url':sku.default_image.url,
                'name':sku.name,
                'price':sku.price
            })

        return JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'hot_skus':hot_skus})

# 详情页
class DetailView(View):
    def get(self, request, sku_id):
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
        }
        return render(request, 'detail.html', context)

# 访问量
class DetailVisitView(View):
    def post(self, request, category_id):
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return HttpResponseNotFound('商品分类不存在')

        # 获取当天日期
        from datetime import datetime
        today_str = datetime.now().strftime('%Y-%m-%d')
        today_date = datetime.strptime(today_str, '%Y-%m-%d')

        from apps.goods.models import GoodsVisitCount
        try:
            count_data = category.goodsvisitcount_set.get(date=today_date)
        except Exception as e:
            count_data = GoodsVisitCount()

        try:
            count_data.count += 1
            count_data.category = category
            count_data.save()
        except Exception as e:
            return HttpResponseNotFound('新增失败')

        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

